package com.sanmubird.mywebframework.indicator.domain.executor;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.Map;


/**
 * @author sam
 */
public class MethodParameterUtil {

    /**
     * 判断是否是java 基础对象
     *
     * @param clz
     * @return
     */
    public static boolean isJavaClass(Class<?> clz) {
        return clz != null && clz.getClassLoader() == null;
    }

    /**
     * 获取方法入参
     *
     * @param clazz
     * @param methodName
     * @return
     */
    public static Map<String, Class> getMethodParameter(Class clazz, String methodName) {
        Map<String, Class> param = new LinkedHashMap<>(16);

        Method[] methods = clazz.getDeclaredMethods();

        for (Method method : methods) {
            if (methodName.equals(method.getName())) {
                //直接通过method就能拿到所有的参数
                Parameter[] params = method.getParameters();
                for (Parameter parameter : params) {
                    param.put(parameter.getName(), parameter.getType());
                }
            }
        }
        return param;
    }

    /**
     * 获取方法返回值
     *
     * @param clazz
     * @param methodName
     * @return
     */
    public static Type getMethodReturnTypeString(Class clazz, String methodName) {

        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            if (methodName.equals(method.getName())) {
                Type type = method.getGenericReturnType();

                if (type instanceof ParameterizedType) {
                    return ((ParameterizedType) type).getRawType();
                }
                return method.getGenericReturnType();
            }
        }
        return null;
    }
}

